package com.ts.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;

/**
 * 日期工具类, 继承org.apache.commons.lang.time.DateUtils类
 */
public class DateUtils extends org.apache.commons.lang.time.DateUtils {
	
	private static String[] parsePatterns = {
		"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", 
		"yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
		"yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM",
		"yyyyMMdd"};

	/**
	 * 得到当前日期字符串 格式（yyyy-MM-dd）
	 */
	public static String getDate() {
		return getDate("yyyy-MM-dd");
	}
	
	/**
	 * 得到当前日期字符串 格式（yyyy-MM-dd） pattern可以为："yyyy-MM-dd" "HH:mm:ss" "E"
	 */
	public static String getDate(String pattern) {
		return DateFormatUtils.format(new Date(), pattern);
	}
	
	/**
	 * 得到日期字符串 默认格式（yyyy-MM-dd） pattern可以为："yyyy-MM-dd" "HH:mm:ss" "E"
	 */
	public static String formatDate(Date date, Object... pattern) {
		String formatDate = null;
		if (pattern != null && pattern.length > 0) {
			formatDate = DateFormatUtils.format(date, pattern[0].toString());
		} else {
			formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
		}
		return formatDate;
	}
	
	/**
	 * 得到日期时间字符串，转换格式（yyyy-MM-dd HH:mm:ss）
	 */
	public static String formatDateTime(Date date) {
		return formatDate(date, "yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 得到当前时间字符串 格式（HH:mm:ss）
	 */
	public static String getTime() {
		return formatDate(new Date(), "HH:mm:ss");
	}

	/**
	 * 得到当前日期和时间字符串 格式（yyyy-MM-dd HH:mm:ss）
	 */
	public static String getDateTime() {
		return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 得到当前年份字符串 格式（yyyy）
	 */
	public static String getYear() {
		return formatDate(new Date(), "yyyy");
	}

	/**
	 * 得到当前月份字符串 格式（MM）
	 */
	public static String getMonthDate() {
		return formatDate(new Date(), "yyyy-MM");
	}
	/**
	 * 得到当前月份字符串 格式（MM）
	 */
	public static String getMonth() {
		return formatDate(new Date(), "MM");
	}

	/**
	 * 得到当天字符串 格式（dd）
	 */
	public static String getDay() {
		return formatDate(new Date(), "dd");
	}

	/**
	 * 得到当前星期字符串 格式（E）星期几
	 */
	public static String getWeek() {
		return formatDate(new Date(), "E");
	}
	
	public static String getHour() {
		return formatDate(new Date(), "HH");
	}
	
	/**
	 * 日期型字符串转化为日期 格式
	 * { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", 
	 *   "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm",
	 *   "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm" }
	 */
	public static Date parseDate(Object str) {
		if (str == null){
			return null;
		}
		try {
			return parseDate(str.toString(), parsePatterns);
		} catch (ParseException e) {
			return null;
		}
	}

	/**
	 * 获取过去的天数
	 * @param date
	 * @return
	 */
	public static long pastDays(Date date) {
		long t = new Date().getTime()-date.getTime();
		return t/(24*60*60*1000);
	}

	/**
	 * 获取过去的小时
	 * @param date
	 * @return
	 */
	public static long pastHour(Date date) {
		long t = new Date().getTime()-date.getTime();
		return t/(60*60*1000);
	}
	
	/**
	 * 获取过去的分钟
	 * @param date
	 * @return
	 */
	public static long pastMinutes(Date date) {
		long t = new Date().getTime()-date.getTime();
		return t/(60*1000);
	}
	
	/**
	 * 转换为时间（天,时:分:秒.毫秒）
	 * @param timeMillis
	 * @return
	 */
    public static String formatDateTime(long timeMillis){
		long day = timeMillis/(24*60*60*1000);
		long hour = (timeMillis/(60*60*1000)-day*24);
		long min = ((timeMillis/(60*1000))-day*24*60-hour*60);
		long s = (timeMillis/1000-day*24*60*60-hour*60*60-min*60);
		long sss = (timeMillis-day*24*60*60*1000-hour*60*60*1000-min*60*1000-s*1000);
		return (day>0?day+",":"")+hour+":"+min+":"+s+"."+sss;
    }
	
	/**
	 * 获取两个日期之间的天数
	 * 
	 * @param before
	 * @param after
	 * @return
	 */
	public static double getDistanceOfTwoDate(Date before, Date after) {
		long beforeTime = before.getTime();
		long afterTime = after.getTime();
		return (afterTime - beforeTime) / (1000 * 60 * 60 * 24);
	}
	
	/** 
     * 获得昨天 
     * @return 
     * @throws Exception 
     */  
    public static String getYesterday() {//可以用new Date().toLocalString()传递参数  
        Calendar c = Calendar.getInstance();  
        c.setTime(new Date());  
        int day = c.get(Calendar.DATE);  
        c.set(Calendar.DATE, day - 1);  
        String dayBefore = new SimpleDateFormat("yyyy-MM-dd").format(c  
                .getTime());  
        return dayBefore;  
    }  
    /** 
     * 获得某天的明天
     * @return 
     * @throws Exception 
     */  
    public static String getTomorrowOfDay(String d) {
    	String dayAfter=null;
    	try{
    		if(StringUtils.isNotBlank(d)){
    			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
                Calendar c = Calendar.getInstance();  
                c.setTime(sdf.parse(d));  
                int day = c.get(Calendar.DATE);  
                c.set(Calendar.DATE, day + 1);  
                dayAfter = sdf.format(c.getTime()); 
    		}
    	}catch(Exception e ){
    		e.printStackTrace();
    	}
    	
    	return dayAfter;  
    } 
    /** 
     * 获得前天 
     * @return 
     * @throws Exception 
     */  
    public static String getYesterday2() {//可以用new Date().toLocalString()传递参数  
        Calendar c = Calendar.getInstance();  
        c.setTime(new Date());  
        int day = c.get(Calendar.DATE);  
        c.set(Calendar.DATE, day - 2);  
        String dayBefore = new SimpleDateFormat("yyyy-MM-dd").format(c  
                .getTime());  
        return dayBefore;  
    } 
    
    /** 
     * 获得明天 
     * @return 
     * @throws Exception 
     */  
    public static String getTomorrow(String d) {
    	String dayBefore=null;
    	try{
    		if(StringUtils.isNotBlank(d)){
    			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
                Calendar c = Calendar.getInstance();  
                c.setTime(sdf.parse(d));  
                int day = c.get(Calendar.DATE);  
                c.set(Calendar.DATE, day+1);  
                dayBefore = sdf.format(c.getTime());  
    		}
    	}catch(Exception e ){
    		e.printStackTrace();
    	}
    	
        return dayBefore;  
    } 
    /** 
     * 获得某天的昨天
     * @return 
     * @throws Exception 
     */  
    public static String getYesterDayOfDay(String d) {
    	String dayBefore=null;
    	try{
    		if(StringUtils.isNotBlank(d)){
    			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
                Calendar c = Calendar.getInstance();  
                c.setTime(sdf.parse(d));  
                int day = c.get(Calendar.DATE);  
                c.set(Calendar.DATE, day-1);  
                dayBefore = sdf.format(c.getTime()); 
    		}
    	}catch(Exception e ){
    		e.printStackTrace();
    	}
    	
    	return dayBefore;  
    } 
    /** 
     * 获得上个月的今天的明天 
     * @return 
     * @throws Exception 
     */  
    public static String getLastMonthOfTomorrow(String d) {
    	String dayBefore=null;
    	try{
    		if(StringUtils.isNotBlank(d)){
    			String todayOfLastMonth=getLastMonthOfDay(d);
    			if(todayOfLastMonth!=null){
    				SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
                    Calendar c = Calendar.getInstance();  
                    c.setTime(sdf.parse(todayOfLastMonth));  
                    int day = c.get(Calendar.DATE);  
                    c.set(Calendar.DATE, day+1);  
                    dayBefore = sdf.format(c.getTime());
    			}
    		}
    	}catch(Exception e ){
    		e.printStackTrace();
    	}
    	
        return dayBefore;  
    } 
    
    /**
     * 获取上个月的这天（yyyy-MM-dd）
     * @author zbb
     * @since 2015-12-24
     * @param day
     * @return
     */
    public static String getLastMonthOfDay(String day){
    	String lastDateStr=null;
    	try{
    		if(StringUtils.isNotBlank(day)){
    			SimpleDateFormat format=new SimpleDateFormat("yyy-MM-dd");
        		Date date=format.parse(day);
        		Calendar c=Calendar.getInstance();
        		c.setTime(date);
        		c.add(Calendar.MONTH, -1);
        		Date lastDate=c.getTime();
        		lastDateStr=format.format(lastDate);
    		}
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    	return lastDateStr;
    }
    /**
     * 获取下个月的这天（yyyy-MM-dd）
     * @author zbb
     * @since 2015-12-24
     * @param day
     * @return
     */
    public static String getNextMonthOfDay(String day){
    	String lastDateStr=null;
    	try{
    		if(StringUtils.isNotBlank(day)){
    			SimpleDateFormat format=new SimpleDateFormat("yyy-MM-dd");
        		Date date=format.parse(day);
        		Calendar c=Calendar.getInstance();
        		c.setTime(date);
        		c.add(Calendar.MONTH, 1);
        		Date lastDate=c.getTime();
        		lastDateStr=format.format(lastDate);
    		}
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    	return lastDateStr;
    }
    /**
     * 获取上下n个月的这天（n为负数则代表上n个月，n为正数则代表下n个月）（yyyy-MM-dd）;
     * @author zbb
     * @since 2015-12-24
     * @param day
     * @return
     */
    public static String getMonthOfDay(String day,int n){
    	String lastDateStr=null;
    	try{
    		SimpleDateFormat format=new SimpleDateFormat("yyy-MM-dd");
			Date date=format.parse(day);
    		Calendar c=Calendar.getInstance();
    		c.setTime(date);
    		c.add(Calendar.MONTH, n);
    		Date lastDate=c.getTime();
    		lastDateStr=format.format(lastDate);
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    	return lastDateStr;
    }
    /**
     * 获取上个月的今天（yyyy-MM-dd）
     * @author zbb
     * @since 2015-12-24
     * @return
     */
    public static String getLastMonthOfToday(){
    	String lastDateStr=null;
    	try{
    		SimpleDateFormat format=new SimpleDateFormat("yyy-MM-dd");
    		Date date=new Date();
    		Calendar c=Calendar.getInstance();
    		c.setTime(date);
    		c.add(Calendar.MONTH, -1);
    		Date lastDate=c.getTime();
    		lastDateStr=format.format(lastDate);
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    	return lastDateStr;
    }
    /**
     * 获取下个月的今天（yyyy-MM-dd）
     * @author zbb
     * @since 2015-12-24
     * @return
     */
    public static String getNextMonthOfToday(){
    	String lastDateStr=null;
    	try{
    		SimpleDateFormat format=new SimpleDateFormat("yyy-MM-dd");
			Date date=new Date();
    		Calendar c=Calendar.getInstance();
    		c.setTime(date);
    		c.add(Calendar.MONTH, 1);
    		Date lastDate=c.getTime();
    		lastDateStr=format.format(lastDate);
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    	return lastDateStr;
    }
    /**
     * 获取上下n个月的今天（n为负数则代表上n个月，n为正数则代表下n个月）（yyyy-MM-dd）;
     * @author zbb
     * @since 2015-12-24
     * @return
     */
    public static String getMonthOfToday(int n){
    	String lastDateStr=null;
    	try{
    		SimpleDateFormat format=new SimpleDateFormat("yyy-MM-dd");
			Date date=new Date();
    		Calendar c=Calendar.getInstance();
    		c.setTime(date);
    		c.add(Calendar.MONTH, n);
    		Date lastDate=c.getTime();
    		lastDateStr=format.format(lastDate);
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    	return lastDateStr;
    }
    
    /**
     * 获取一周前日期（yyyy-MM-dd）
     * @author mjj
     * @since 2016-03-17
     * @return
     */
    public static String getDayOfLastWeek(){
    	Calendar c = Calendar.getInstance();  
        c.setTime(new Date());  
        int day = c.get(Calendar.DATE);  
        c.set(Calendar.DATE, day - 7);  
        String dayOfLastWeek = new SimpleDateFormat("yyyy-MM-dd").format(c  
                .getTime());  
        return dayOfLastWeek;  
    	
    }
    
    /**
     * 获取给定日期范围内的所有日期list,格式：yyyy-MM-dd
     * @param startDate
     * @param endDate
     * @return
     */
    public static List<String> getBetweenDate(String startDate,String endDate) throws Exception{
    	List<String> list=new ArrayList<String>();
    	Date date_start=parseDate(startDate);
    	Date date_end=parseDate(endDate);
    	//日期范围不能为空，且endDate必须大于等startDate
    	if(StringUtils.isNotBlank(startDate)&&StringUtils.isNotBlank(endDate)&&date_end.compareTo((date_start))>=0){
    		Calendar calStart = Calendar.getInstance();
    		calStart.setTime(date_start);
    		Calendar calEnd = Calendar.getInstance();
    		calEnd.setTime(date_end);
    		while (true) {
    			list.add(formatDate(calStart.getTime(),"yyyy-MM-dd"));
    			if (calStart.get(Calendar.YEAR) == calEnd.get(Calendar.YEAR)
    					&& calStart.get(Calendar.MONTH) == calEnd
    							.get(Calendar.MONTH)
    					&& calStart.get(Calendar.DATE) == calEnd
    							.get(Calendar.DATE)) {
    				break;
    			}
    			calStart.add(Calendar.DAY_OF_YEAR, 1);
    		}
    	}
		return list;
    }
    /**
     * 获取给定日期范围内的所有日期list,格式：yyyy-MM
     * @param startDate
     * @param endDate
     * @return
     */
    public static List<String> getBetweenMonth(String startDate,String endDate) throws Exception{
    	List<String> list=new ArrayList<String>();
    	SimpleDateFormat format=new SimpleDateFormat("yyyy-MM");
    	Date date_start=format.parse(startDate);
    	Date date_end=format.parse(endDate);
    	//日期范围不能为空，且endDate必须大于等startDate
    	if(StringUtils.isNotBlank(startDate)&&StringUtils.isNotBlank(endDate)&&date_end.compareTo((date_start))>=0){
    		Calendar calStart = Calendar.getInstance();
    		calStart.setTime(date_start);
    		Calendar calEnd = Calendar.getInstance();
    		calEnd.setTime(date_end);
    		while (true) {
    			list.add(formatDate(calStart.getTime(),"yyyy-MM"));
    			if (calStart.get(Calendar.YEAR) == calEnd.get(Calendar.YEAR)
    					&& calStart.get(Calendar.MONTH) == calEnd
    							.get(Calendar.MONTH)
    					) {
    				break;
    			}
    			calStart.add(Calendar.MONTH, 1);
    		}
    	}
		return list;
    }
    /**
     * 获取给定日期范围内的所有日期list,格式：yyyy
     * @param startDate
     * @param endDate
     * @return
     */
    public static List<String> getBetweenYear(String startDate,String endDate) throws Exception{
    	List<String> list=new ArrayList<String>();
    	SimpleDateFormat format=new SimpleDateFormat("yyyy");
    	Date date_start=format.parse(startDate);
    	Date date_end=format.parse(endDate);
    	//日期范围不能为空，且endDate必须大于等startDate
    	if(StringUtils.isNotBlank(startDate)&&StringUtils.isNotBlank(endDate)&&date_end.compareTo((date_start))>=0){
    		Calendar calStart = Calendar.getInstance();
    		calStart.setTime(date_start);
    		Calendar calEnd = Calendar.getInstance();
    		calEnd.setTime(date_end);
    		while (true) {
    			list.add(formatDate(calStart.getTime(),"yyyy"));
    			if (calStart.get(Calendar.YEAR) == calEnd.get(Calendar.YEAR)) {
    				break;
    			}
    			calStart.add(Calendar.YEAR, 1);
    		}
    	}
		return list;
    }
    
    /** 
     * 获得指定某天的前后n天 
     * @return 
     * @throws Exception 
     */  
    public static String getDayOfDate(String date,int n) {
    	String datenext=null;
    	try{
    		if(StringUtils.isNotBlank(date)){
    			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
                Calendar c = Calendar.getInstance();  
                c.setTime(sdf.parse(date));  
                int day = c.get(Calendar.DATE);  
                c.set(Calendar.DATE, day+n);  
                datenext = sdf.format(c.getTime());  
    		}
    	}catch(Exception e ){
    		e.printStackTrace();
    	}
    	
        return datenext;  
    } 
    /**
     * 获取指定月的前后n月
     * @author zbb
     * @since 2015-12-24
     * @return
     */
    public static String getMonthOfTheMothe(String month,int n){
    	String monthnext=null;
    	try{
    		if(StringUtils.isNotBlank(month)){
    			SimpleDateFormat format=new SimpleDateFormat("yyyy-MM");
    			Calendar c = Calendar.getInstance();
    			c.setTime(format.parse(month));
        		c.add(Calendar.MONTH, n);
        		Date lastDate=c.getTime();
        		monthnext=format.format(lastDate);
    		}
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    	return monthnext;
    }
    /**
     * 获取指定年的前后n年
     * @author zbb
     * @since 2015-12-24
     * @return
     */
    public static String getYearOfTheYear(String year,int n){
    	String yearnext=null;
    	try{
    		if(StringUtils.isNotBlank(year)){
    			SimpleDateFormat format=new SimpleDateFormat("yyyy");
    			Calendar c = Calendar.getInstance();
    			c.setTime(format.parse(year));
        		c.add(Calendar.YEAR, n);
        		Date lastDate=c.getTime();
        		yearnext=format.format(lastDate);
    		}
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    	return yearnext;
    }
    /**
     * 获取给定日期范围内的天数
     * @param startDate
     * @param endDate
     * @return
     */
    public static int getBetweenDateNum(String startDate,String endDate) throws Exception{
    	int num=0;
    	SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
    	Date date_start=format.parse(startDate);
    	Date date_end=format.parse(endDate);
    	//日期范围不能为空，且endDate必须大于等startDate
    	if(StringUtils.isNotBlank(startDate)&&StringUtils.isNotBlank(endDate)&&date_end.compareTo((date_start))>=0){
    		Calendar calStart = Calendar.getInstance();
    		calStart.setTime(date_start);
    		Calendar calEnd = Calendar.getInstance();
    		calEnd.setTime(date_end);
    		while (true) {
    			num++;
    			if (calStart.get(Calendar.YEAR) == calEnd.get(Calendar.YEAR)
    					&& calStart.get(Calendar.MONTH) == calEnd
    							.get(Calendar.MONTH)
    					&& calStart.get(Calendar.DATE) == calEnd
    							.get(Calendar.DATE)) {
    				break;
    			}
    			calStart.add(Calendar.DATE, 1);
    		}
    	}
		return num;
    }
    /**
     * 获取给定月份范围内的月数
     * @param startDate
     * @param endDate
     * @return
     */
    public static int getBetweenMonthNum(String startMonth,String endMonth) throws Exception{
    	int num=0;
    	SimpleDateFormat format=new SimpleDateFormat("yyyy-MM");
    	Date date_start=format.parse(startMonth);
    	Date date_end=format.parse(endMonth);
    	//日期范围不能为空，且endDate必须大于等startDate
    	if(StringUtils.isNotBlank(startMonth)&&StringUtils.isNotBlank(endMonth)&&date_end.compareTo((date_start))>=0){
    		Calendar calStart = Calendar.getInstance();
    		calStart.setTime(date_start);
    		Calendar calEnd = Calendar.getInstance();
    		calEnd.setTime(date_end);
    		while (true) {
    			num++;
    			if (calStart.get(Calendar.YEAR) == calEnd.get(Calendar.YEAR)
    					&& calStart.get(Calendar.MONTH) == calEnd
    							.get(Calendar.MONTH)
    					) {
    				break;
    			}
    			calStart.add(Calendar.MONTH, 1);
    		}
    	}
		return num;
    }
    
    /**
     * 获取给定年份范围内的年数
     * @param startDate
     * @param endDate
     * @return
     */
    public static int getBetweenYearNum(String startYear,String endYear) throws Exception{
    	int num=0;
    	SimpleDateFormat format=new SimpleDateFormat("yyyy");
    	Date date_start=format.parse(startYear);
    	Date date_end=format.parse(endYear);
    	//日期范围不能为空，且endDate必须大于等startDate
    	if(StringUtils.isNotBlank(startYear)&&StringUtils.isNotBlank(endYear)&&date_end.compareTo((date_start))>=0){
    		Calendar calStart = Calendar.getInstance();
    		calStart.setTime(date_start);
    		Calendar calEnd = Calendar.getInstance();
    		calEnd.setTime(date_end);
    		while (true) {
    			num++;
    			if (calStart.get(Calendar.YEAR) == calEnd.get(Calendar.YEAR)) {
    				break;
    			}
    			calStart.add(Calendar.YEAR, 1);
    		}
    	}
		return num;
    }
    
    /** 
     * 获得某月的前后n月
     * @return 
     * @throws Exception 
     */  
    public static String getMothOfTheMonth(String month,int n) {
    	String dayAfter=null;
    	try{
    		if(StringUtils.isNotBlank(month)){
    			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM");
                Calendar c = Calendar.getInstance();  
                c.setTime(sdf.parse(month));  
                c.add(Calendar.MONTH, n);  
                dayAfter = sdf.format(c.getTime()); 
    		}
    	}catch(Exception e ){
    		e.printStackTrace();
    	}
    	
    	return dayAfter;  
    } 
    /** 
     * 获得某月的前后n月
     * @return 
     * @throws Exception 
     */  
    public static String getYearfTheYear(String year,int n) {
    	String dayAfter=null;
    	try{
    		if(StringUtils.isNotBlank(year)){
    			SimpleDateFormat sdf=new SimpleDateFormat("yyyy");
                Calendar c = Calendar.getInstance();  
                c.setTime(sdf.parse(year)); 
                c.add(Calendar.YEAR, n); 
                dayAfter = sdf.format(c.getTime()); 
    		}
    	}catch(Exception e ){
    		e.printStackTrace();
    	}
    	
    	return dayAfter;  
    }
    
	/**
	 * @param args
	 * @throws ParseException
	 */
	public static void main(String[] args) throws ParseException {
    	try{
    		System.out.println(getYearfTheYear("2017",-10));
    	}catch(Exception e ){
    		e.printStackTrace();
    	}
    	
	}
}
